//
//  VideoListTableController.m
//  Video
//
//  Created by lanou3g on 16/5/11.
//  Copyright © 2016年 liu. All rights reserved.
//

#import "VideoListTableController.h"
#import "NetWorkRequestManager.h"
#import "VideoListModel.h"
#import "VideoListModelCell.h"
#import "LORefresh.h"
#import "VideoPlayView.h"
#import <AVFoundation/AVFoundation.h>
#import "PlayerViewController.h"
#import "UserInfoManager.h"
#import "LoginViewController.h"
// 分享
#import "UMSocial.h"



@interface VideoListTableController ()<didClickPlayerDelegate,VideoPlayViewDelegate,UMSocialUIDelegate>

@property (nonatomic,strong) NSMutableArray *dataSource;

@property (nonatomic,strong) NSString *start;

@property (nonatomic,strong) VideoPlayView *playerView;

@property (nonatomic,strong) VideoListModelCell *playerCell;

@property (nonatomic,strong) NSString *mp4Str;


@end

@implementation VideoListTableController


- (void)dealloc {
    [self.tableView removeObserver:[self.tableView defaultHeader] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentSize"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    
    self.dataSource = [NSMutableArray array];
    
    self.start = @"10";
    [self analyticalData];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"VideoListModelCell" bundle:nil] forCellReuseIdentifier:@"VideoListModel"];
    
    [self addRefresh];
    
    
    self.navigationItem.title = @"视频";
    
}
/// 加载、刷新
- (void)addRefresh {
    __weak typeof(self)weakSelf = self;
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
        [weakSelf.dataSource removeAllObjects];
        [weakSelf.tableView reloadData];
        [weakSelf analyticalData];
    }];
    
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        NSInteger count = weakSelf.dataSource.count;
        weakSelf.start = [NSString stringWithFormat:@"%ld",count];
        [weakSelf analyticalData];
    }];
    
}
- (void)analyticalData {
    NSString *str = @"http://c.3g.163.com/recommend/getChanListNews?channel=T1457068979049&size=10&passport=&devId=8wv%2B6dOeOzvcR5U8%2BYZg5w%3D%3D&lat=TRHjW5%2FfEY2uznlYAcdU5g%3D%3D&lon=raSd6u7XWdwjVFk1yCRotg%3D%3D&version=7.0&net=wifi&ts=1462345298&sign=MCrGDZCZNU%2BiH%2FuLwUdKp2WpyK0QXo%2BMY7GeaIEjR7t48ErR02zJ6%2FKXOnxX046I&encryption=1&canal=360_news";
    [NetWorkRequestManager requestUrl:[NSURL URLWithString:str] RequestMethod:GET Params:nil Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            NSMutableDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSArray *array = jsonDic[@"视频"];
            for (NSDictionary *dic in array) {
                
                self.mp4Str = dic[@"mp4_url"];
                VideoListModel *model = [[VideoListModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                NSLog(@"%@",model.mp4_url);
                [self.dataSource addObject:model];
            }
            NSLog(@"%ld",self.dataSource.count);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                [[self.tableView defaultHeader]endRefreshing];
                [[self.tableView defaultFooter]endRefreshing];
            });
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    VideoListModelCell *cell = [tableView dequeueReusableCellWithIdentifier:@"VideoListModel" forIndexPath:indexPath];
    
    [cell.shareButton addTarget:self action:@selector(didClickShareButton) forControlEvents:UIControlEventTouchUpInside];
    [cell.commentsButton addTarget:self action:@selector(didClickCommentsButton) forControlEvents:UIControlEventTouchUpInside];
    
    cell.model = self.dataSource[indexPath.row];
    cell.indexPath = indexPath;
    cell.playerDelegate = self;
    
    return cell;
}

-(void)didClickShareButton{
    if ([UserInfoManager shareManager].uid) {
        [UMSocialSnsService presentSnsIconSheetView:self appKey:@"564913af67e58ed0d7005bb3" shareText:self.mp4Str shareImage:[UIImage imageNamed:@"coin"] shareToSnsNames:[NSArray arrayWithObjects:UMShareToDouban,UMShareToTencent,UMShareToRenren,UMShareToSina,UMShareToQQ,UMShareToWechatSession, nil] delegate:self];
    } else {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请先登录" preferredStyle:UIAlertControllerStyleAlert];
        [alertC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self login];
        }]];
        [alertC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }]];
        [self presentViewController:alertC animated:YES completion:nil];
    }
    
}


- (void)login {
    LoginViewController *loginVC = [[LoginViewController alloc]init];
    [self.navigationController pushViewController:loginVC animated:YES];
}


-(void)didClickCommentsButton{
    PlayerViewController *playerVC = [[PlayerViewController alloc]init];
    [self.navigationController pushViewController:playerVC animated:YES];
    
}

-(void)clickVideoButton:(NSIndexPath *)indexPath{
    [self.playerView resetPlayView];
    VideoListModelCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    self.playerCell = cell;
    VideoPlayView *playView = [VideoPlayView videoPlayView];
    VideoListModel *model = self.dataSource[indexPath.row];
    playView.frame = CGRectMake(10, 49, 398, 193);
    [cell addSubview:playView];
    cell.playerView = playView;
    self.playerView = playView;
    self.playerView.delegate = self;
    
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:model.mp4_url]];
    self.playerView.playerItem = item;
}

-(void)videoplayViewSwitchOrIebtation:(BOOL)isFull{
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 300;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    PlayerViewController *playerVC = [[PlayerViewController alloc]init];
    playerVC.index = indexPath.row;
    
    playerVC.model = self.dataSource[indexPath.row];
    playerVC.videoArray = self.dataSource;
    VideoListModel *model = self.dataSource[indexPath.row];
    playerVC.groupID = model.replyid;
//    [self presentViewController:playerVC animated:YES completion:nil];
    [self.navigationController pushViewController:playerVC animated:YES];
    
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
